package bjtu.tjj.simpledy.service.impl;

import bjtu.tjj.simpledy.common.ResultCode;
import bjtu.tjj.simpledy.exception.CommonException;
import bjtu.tjj.simpledy.mapper.LikeMapper;
import bjtu.tjj.simpledy.mapper.VideoMapper;
import bjtu.tjj.simpledy.service.LikeService;
import bjtu.tjj.simpledy.utils.ThreadLocalUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class LikeServiceImpl implements LikeService {
    private final LikeMapper likeMapper;
    private final VideoMapper videoMapper;

    @Override
    public int add(Long videoId) {
        if (!videoMapper.exists(videoId)) {
            throw new CommonException(ResultCode.VIDEO_NOT_EXIST);
        }
        int res = likeMapper.insert(ThreadLocalUtils.getUserId(), videoId);
        if (res == 0) {
            throw new CommonException(ResultCode.ALREADY_LIKED);
        }
        Integer count = videoMapper.getReceivedLikeCountById(videoId);
        if (count == null) {
            throw new CommonException(ResultCode.VIDEO_NOT_EXIST);
        }
        return count;
    }

    @Override
    public int delete(Long videoId) {
        if (!videoMapper.exists(videoId)) {
            throw new CommonException(ResultCode.VIDEO_NOT_EXIST);
        }
        int res = likeMapper.delete(ThreadLocalUtils.getUserId(), videoId);
        if (res == 0) {
            throw new CommonException(ResultCode.NOT_LIKE_YET);
        }
        Integer count = videoMapper.getReceivedLikeCountById(videoId);
        if (count == null) {
            throw new CommonException(ResultCode.VIDEO_NOT_EXIST);
        }
        return count;
    }
}
